package course7.com.youkeda.service.impl;

import course7.com.youkeda.model.Page;
import course7.com.youkeda.model.Student;
import course7.com.youkeda.service.StudentService;

import java.util.ArrayList;
import java.util.List;

public class StudentServiceImpl implements StudentService {
    private  static  List<Student> STUDENTS=new ArrayList<>();
    private  static int pageSize=3;
    @Override
    public void add(Student student) {
        STUDENTS.add(student);

    }

    @Override
    public List<Student> getAll() {
        return STUDENTS;
    }

    @Override
    public Page<Student> query(int pageNumber) {
        int totalElements=getAll().size();
        // 计算总页面数
        int totalPages = 0;
// 如果能够整除，那么页数就是相除的值
// 比如 6%3 = 0，那么页数就是 6/3=2
        if (totalElements % pageSize == 0) {
            totalPages = totalElements / pageSize;
        } else {
            //如果不能整除，就在除的结果上+1，比如 9%10 = 9 ,页面数 9/10 +1 =1
            totalPages = totalElements / pageSize + 1;
        }

// 计算开始和结束
        int begin =  (pageNumber-1) * pageSize;
        int end = pageNumber * pageSize;
        if ( totalElements < end){
            end = totalElements;
        }

        List<Student> students = getAll().subList( begin,end );
        Page<Student> page = new Page(pageSize,totalPages,totalElements,pageNumber,students);
        return page;
    }
}
